package com.gky.gkytemplate.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gky.gkytemplate.common.constant.FileConstant;
import com.gky.gkytemplate.common.context.BaseContext;
import com.gky.gkytemplate.common.enums.ErrorCode;
import com.gky.gkytemplate.common.enums.FileUploadEnum;
import com.gky.gkytemplate.common.exception.BusinessException;
import com.gky.gkytemplate.common.manager.CosManager;
import com.gky.gkytemplate.common.result.Result;
import com.gky.gkytemplate.pojo.dto.file.FileUploadRequest;
import com.gky.gkytemplate.utils.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    @PostMapping("/upload")
    public Result<String> uploadFile(@RequestPart("file") MultipartFile multipartFile, FileUploadRequest fileUploadRequest) {
        ThrowUtils.throwIf(StringUtils.isBlank(fileUploadRequest.getValue()), ErrorCode.NOT_FOUND_ERROR);
        //UUID-文件上传类型 如user_avatar
        String fileValue = UUID.randomUUID() + "-" + fileUploadRequest.getValue();
        //文件类型枚举
        FileUploadEnum fileUploadEnum = FileUploadEnum.getEnumByValue(fileValue);

        //原始文件名.文件扩展类型
        String filename = multipartFile.getOriginalFilename();
        validFile(multipartFile, fileUploadEnum);
        String filepath = String.format("/%s/%s/%s", fileUploadEnum.getValue(), BaseContext.getCurrentId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return Result.ok(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    private void validFile(MultipartFile multipartFile, FileUploadEnum fileUploadEnum) {
        //文件最大能上传的大小
        Long fileSize = fileUploadEnum.getFileSize();
        //文件实际大小
        long size = multipartFile.getSize();
        //文件类型编码
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());

        if (FileUploadEnum.USER_AVATAR.equals(fileUploadEnum)){
            if (size > fileSize) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过" + fileSize);
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(suffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
